
const {ErrorModel,SuccessModel} =require('../model/resModel')

const {exec} =require('../db/mysql')

const {decrypt,genPassword}=require('../utils/util')

const axios =require('axios')

const jwt = require('jsonwebtoken');

const TOKEN_SECRETKEY = 'token_666666'



//用户表的列名（除去了密码）
const usersColumns = [
    'id',
    'username',
    'registrationAddress',
    'registrationTime',
    'lastLoginAddress',
    'lastLoginTime',
    'isAdmin',
    'avatar',
    'birth',
    'phone',
    'location',
    'gender',
]



/***
 * 检查用户名是否存在
 * @param {string} username 
 * **/
const checkName=async (username)=>{
    const sql=`select username from users where username='${username}'`;
    const res =await exec(sql).then(data=>{
        return data 
    });
    console.log(res.length,"res")
    return new SuccessModel({
        data:{num:res.length}
    })
}


/*** 获取ip getIpInfo
 * @param {string} 
 * ***/
 const getIpInfo=async (ctx)=>{
    const ip = ctx.ip.split(':').pop() 
    
    const res = await axios.get('https://apis.map.qq.com/ws/location/v1/ip', {
        params: {
            key: 'MH2BZ-4WTK3-2D63K-YZRHP-HM537-HHBD3',
            // ip //本地测试时ip一直是:::1，所以先注释掉
        }
    })

    if (res.data.status === 0) {
        return new SuccessModel({
            data: res.data.result
        })
    } else {
        return new ErrorModel({
            message: '获取ip地址失败',
            httpCode: 500
        })
    }
 }


/**
 * 登录接口
 * @param {*} username
 * @param {*} password
 * @param {*} ctx
 * **/
const loginApi=async (username,password,ctx)=>{
    //检查用户名是否存在
    const checkNameResult= await checkName(username)
    if(!checkNameResult.data.num){
        return new ErrorModel({
            msg:'用户名不存在',
            httpCode:"400"
        })
    }

    //用户名存在开始操作

    // //先解密前端加密的密码
    // const originalText = decrypt(password)
    // //然后再用另一种方式加密密码
    // const ciphertext = genPassword(originalText)
    const sql = `select username from users where username='${username}' and password='${password}'`
    const res=await exec(sql).then(data=> {return data});

   if(!res.length){
       return new ErrorModel({
           msg:"密码错误",
           httpCode:400
       })
   }

   const ip=await getIpInfo(ctx)

   if(ip.status!==0){
       return new ErrorModel({
           msg:"获取ip地址失败",
           httpCode:500
       })
   }
   const lastLoginAddress = JSON.stringify(ip.data)


   const sql2 = `update users set lastLoginAddress='${lastLoginAddress}',lastLoginTime='${Date.now()}' where username='${username}'`
   const res2 = await exec(sql2).then(data=>{return data})
   return new SuccessModel({
    message: '登陆成功',
    data: {
        uesrname: res[0].username,
        token: jwt.sign({ username }, TOKEN_SECRETKEY, { expiresIn: '7d' })   //7天过期时间
    }
})
}


/**注册接口
 * @param {*} username
 * @param {*} password
 * @param {*} ctx
 * **/
const registerApi=async (username,password,ctx)=>{

     if(!username ||!password){
         return new ErrorModel({
             msg:"请输入用户名和密码",
             httpCode:400
         })
     }
    // 检查用户名是否已存在
     const checkNameResult= await checkName(username)
     if(checkNameResult.data.num){
         return new ErrorModel({
             msg:'用户名已存在',
             httpCode:"400"
         })
     }

     const ip=await getIpInfo(ctx)
     if(ip.status!==0){
        return new ErrorModel({
            msg: '获取IP地址失败',
            httpCode: 500
        })
     }

     const registrationAddress = JSON.stringify(ip.data)


     const regSql=`insert into users (username,password,registrationAddress,registrationTime) values ('${username}','${password}','${registrationAddress}',${Date.now()})`
     

     const res=await exec(regSql).then(data=>{return data})

 
     //插入数据


     if(res.affectedRows){
         return new SuccessModel({
             data:{userId:res.inserId},
             msg:"注册成功"
         })
     }
     return new ErrorModel({
        httpCode:400,
        msg:"注册失败"
    })
}

/**
 *获取所有的用户接口
 * @param {*} ctx
 * 
**/
const   getAllUsersApi=async (ctx)=>{
    const  sql=`select id,username,password,avatar,isAdmin from cylx.users order by registrationTime desc`
    const res=await exec(sql)
    return new SuccessModel({
        data:res
    })
}

const getUserApi=async (params)=>{
    console.log(params)
   const {username,id,ctx}=params;
   if(!username || !id){
       return new ErrorModel({
           msg:"参数错误"
       })
   }
   let sql =`select  ${usersColumns} from users where`

   if(id){
      sql+= ` id=${id}`
   }else if(username){
    sql+= ` username=${username}`
   }
   const res=await exec(sql)
   return new SuccessModel({
       data:res[0]
   })
}


const getUsersApi= async (param)=>{
   const { current = 0, pageSize = 10, username, startTime, endTime } = param
   let sql = `select SQL_CALC_FOUND_ROWS ${usersColumns.join(',')} from users where registrationTime between ${startTime || 0} and ${endTime || Date.now()} `
   if (username) {
    sql += `and username like '%${username}%' `
   }
    sql += `order by registrationTime desc limit ${current * pageSize},${pageSize}`
    const res = await exec(sql)
    const sql2 = 'select found_rows() as total'
    const res2 = await exec(sql2)
    
    return new SuccessModel({
        data: {
            list: res,
            current: parseInt(current),
            pageSize: parseInt(pageSize),
            total: res2[0].total
        }
    })

}


module.exports={
    loginApi,
    registerApi,
    getAllUsersApi,
    getUsersApi,
    getUserApi
}